package models

import (
	"fmt"
	"rongyy/src/app"
	"rongyy/src/middlewares"
)

type YktOrdersModel struct {
	BaseModel  `xorm:"extends"`
	PayOrderId string `json:"pay_order_id"`
	MchOrderId string `json:"mch_order_id"`
	//IdNumberOrder string `json:"id_number_order"`
	TransactionId string  `json:"transaction_id"`
	OrderAmount   float64 `json:"orderAmount"`
	IdNameOrder   string  `json:"id_name_order"`
	PayNo         string  `json:"pay_no"`
	PatientId     string  `json:"patient_id"`
}

func (pm *YktOrdersModel) TableName() string {
	return "ykt_pay_orders"
}

func (rm *YktOrdersModel) Insert() (*YktOrdersModel, error) {
	_, err := app.DB().Insert(rm)
	if err != nil {
		middlewares.Logger.Println("insert user fail", err)
		return nil, err
	}
	return rm, err
}
func (rm *YktOrdersModel) FindByOrderSn(OrderSn string) (*YktOrdersModel, error) {
	ncm := &YktOrdersModel{}
	has, err := app.DB().Where("mch_order_id=?", OrderSn).Get(ncm)
	if !has {
		return nil, fmt.Errorf("不存在")
	}
	if err != nil {
		return nil, err
	}
	return ncm, nil
}

func (rm *YktOrdersModel) Query(cardNo string) ([]YktOrdersModel, int64, error) {
	cms := make([]YktOrdersModel, 0)
	s := app.DB().Table("ykt_pay_orders").Where("card_no=? and is_used=0", cardNo)
	total, err := s.Limit(999, 0).Limit(1).Desc("created_at").FindAndCount(&cms)
	if err != nil {
		return nil, 0, err
	}
	return cms, total, err
}
